package com.cn.wanxi.controller;

import com.cn.wanxi.common.RedisNumTool;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@RestController
public class CodeController {
    @RequestMapping("/code")
    protected void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //创建空白图片
        BufferedImage image = new BufferedImage(60, 30, BufferedImage.TYPE_3BYTE_BGR);

        /*1.获取图片画笔*/
        Graphics g = image.getGraphics();
        Random r = new Random();

        /*2.设置画笔颜色*/
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

        /*3.绘制矩形背景*/
        g.fillRect(0, 0, 60, 30);

        /*4.调用自定义方法，获取长度为4的数字字母组合的字符串*/
        String number = getNumber(4);
        Jedis jedis = new Jedis();
        jedis.select(RedisNumTool.REDIS_LOGIN_CODE);
        jedis.set("code",number);

        g.setColor(Color.BLUE);
        /*5.设置颜色字体，绘制字符串*/
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font("宋体", Font.BOLD, 24));
        g.drawString(number, 5, 20);

        /*6.绘制干扰线*/
        for (int i = 0; i < 10; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
            //(a,b,x,y)，a，b代表起点，x，y代表终点
        }

        /*7.写入输出流*/
        resp.setContentType("image/jpeg");
        OutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image, "jpeg", outputStream);
        outputStream.close();
    }

    private String getNumber(int size) {
        String str = "qwertyupasdfghjklzxcvbnm0123456789";
        StringBuilder number = new StringBuilder();
        Random r = new Random();
        int length = str.length();
        for (int j = 0; j < size; j++) {
            int le = r.nextInt(length);         //str长度之间的随机数
            char s = str.charAt(le);            //获取到str对应下标的字符
            number.append(s);                   //字符串拼接
        }
        return number.toString();
    }
}
